package com.hsd.app.action;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsd.app.model.HsdImages;
import com.hsd.app.service.IDataManageService;
import com.hsd.commons.helper.UeditorUploader;
import com.hsd.commons.helper.UploadHelper;
import com.hsd.commons.model.HsdAccount;
import com.hsd.core.base.action.BaseAction;
import com.hsd.core.page.entity.PageParams;
import com.hsd.core.page.entity.Pagination;
import com.hsd.core.utils.TimeUtil;
import com.hsd.core.utils.UUIDGenerator;
@Controller
@RequestMapping("/datamanage")
public   class ImageAction extends BaseAction{
	 
	@Autowired
	private IDataManageService hpdataService;
	
	
	/**
	 * 数据管理 ：图片列表
	 * @param pageParams
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/loadImageList.do")
	public String loadImageList(PageParams pageParams,HttpServletRequest request,ModelMap model){
		String namestr = request.getParameter("namestr"); 
		String keyword = request.getParameter("keyword");  
		String catagory = request.getParameter("catagory");  
		Pagination page = this.hpdataService.loadImagesList(pageParams,namestr,keyword,catagory);
		
		model.addAttribute("page",page);
		model.addAttribute("namestr",namestr); 
		model.addAttribute("keyword",keyword); 
		model.addAttribute("catagory",catagory); 
		return "app/data/data-images-list";
	} 
	/**
	 * 新增一个图片
	 * @param request
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/saveOneImage.do")
	public @ResponseBody String saveOneImage(HttpServletRequest request,Model model) throws IOException{
		HsdImages imagesInfo = new HsdImages();
		HsdAccount accInfo = this.getCurrentuser(request);
		//String datatype = URLDecoder.decode(request.getParameter("datatype"), "utf-8");
		//String sep = System.getProperty("file.separator");
		String id_Unicode = request.getParameter("id");
		String namestr_Unicode = request.getParameter("namestr");
		String keyword_Unicode = request.getParameter("keyword");
		String groupname_Unicode = request.getParameter("groupname");
		String imagetype_Unicode = request.getParameter("imagetype");
		String memo_Unicode = request.getParameter("memo");
		
		// 组织图片信息
		String id = StringUtils.isBlank(id_Unicode)? id_Unicode : URLDecoder.decode(id_Unicode, "utf-8");
		String namestr = StringUtils.isBlank(namestr_Unicode)? namestr_Unicode : URLDecoder.decode(namestr_Unicode, "utf-8");
		String keyword = StringUtils.isBlank(keyword_Unicode)? keyword_Unicode : URLDecoder.decode(keyword_Unicode, "utf-8");
		String groupname = StringUtils.isBlank(groupname_Unicode)? groupname_Unicode : URLDecoder.decode(groupname_Unicode, "utf-8");
		String memo = StringUtils.isBlank(memo_Unicode)? memo_Unicode : URLDecoder.decode(memo_Unicode, "utf-8");
		String imagetype = StringUtils.isBlank(imagetype_Unicode)? imagetype_Unicode : URLDecoder.decode(imagetype_Unicode, "utf-8");
		if(StringUtils.isNotEmpty(id)){
			imagesInfo = (HsdImages)this.hpdataService.findByID(HsdImages.class, id);
		}else{
			imagesInfo.setId(UUIDGenerator.getUUID());
		}
		imagesInfo.setNamestr(namestr);
		imagesInfo.setGroupname(groupname);
 		imagesInfo.setKeyword(keyword);
		imagesInfo.setMemo(memo);
		imagesInfo.setOpertime(TimeUtil.getCurrentDate());
		if(null != accInfo){
			imagesInfo.setUserid(accInfo.getId());
			imagesInfo.setUsername(accInfo.getUsername());
		}
		
		String haveFile = request.getParameter("haveFile");
		if(!"0".equals(haveFile)){ // 有文件
			List<FileItem> fileList = null;
			try {
				fileList = UploadHelper.getUploadFileList(request,UploadHelper.SIZE_THRESHOLD);
			} catch (FileUploadException e) {
				e.printStackTrace();
				throw new RuntimeException();
			}
			
			// 处理保存文件
			String realFileName = null; // 上传时文件名
			Iterator<FileItem> it = fileList.iterator();
			while (it.hasNext()) {
				FileItem item = it.next();
				if (!item.isFormField()) {
					realFileName = item.getName();
					if (null == realFileName || "".equals(realFileName.trim())) {
						continue;
					}
					//String imagetype = realFileName.substring(realFileName.lastIndexOf("."));
					imagesInfo.setImagetype(imagetype);
					imagesInfo.setContent(item.get());
				}
			}
		}
		
		hpdataService.save(imagesInfo);  
		
		/*Map query = new HashMap();
		query.put("namestr", imagesInfo.getNamestr()); 
		Object existData = hpdataService.getUniqueObject(HsdImages.class, query);
		if(null != existData){
			return "-1";
		}
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		 MultipartFile multipartFile = multipartRequest.getFile("imgfile");   
		
 		 String fileName = multipartFile.getOriginalFilename(); 
		 String datatype = request.getParameter("datatype");  
		 String sep = System.getProperty("file.separator");
//		//fbobj.setIsuse(1l);
		HsdAccount accInfo = this.getCurrentuser(request);
        String id = request.getParameter("id");
 		String namestr = request.getParameter("namestr");
 		String keyword = request.getParameter("keyword");
		String catagory = request.getParameter("catagory");
		String groupname = request.getParameter("groupname");
		String memo = request.getParameter("memo");
 		//Long id = this.checkAndSaveSynames(request, null, hpdataService, hpName, 1, 5);
		if(StringUtils.isNotEmpty(id)){
			imagesInfo = (HsdImages)this.hpdataService.findByID(HsdImages.class, id);
		}else{
			imagesInfo.setId(UUIDGenerator.getUUID());  
		}
		imagesInfo.setNamestr(namestr);
		imagesInfo.setGroupname(groupname);
 		imagesInfo.setKeyword(keyword);
		imagesInfo.setMemo(memo);
		imagesInfo.setImagetype(catagory);
		imagesInfo.setContent( new String(multipartFile.getBytes()));
		imagesInfo.setOpertime(TimeUtil.getCurrentDate());
		if(null != accInfo){
			imagesInfo.setUserid(accInfo.getId());
			imagesInfo.setUsername(accInfo.getUsername());
		}
		hpdataService.saveObject(imagesInfo);  
		return imagesInfo.getId().toString();*/
		return imagesInfo.getId();
	}
	/**
	 * 删除图片
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/delImage.do",produces = {"application/json;charset=UTF-8"})
	public @ResponseBody String delOneHp(HttpServletRequest request,ModelMap model){
		String id = request.getParameter("id"); 
		HsdImages imagesInfo = new HsdImages();
		imagesInfo.setId(id);
		hpdataService.deleteObject(imagesInfo);
		return "删除成功！";
	}
	
	/**
	 * 查看图片
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/viewImage.do",produces = {"application/json;charset=UTF-8"})
	public String viewImage(HttpServletRequest request,ModelMap model){
		String id = request.getParameter("id"); 
		HsdImages imagesInfo = (HsdImages)hpdataService.findByID(HsdImages.class, id);
		model.addAttribute("mdobj",imagesInfo);
		return "app/data/view-one-image";
	}
	
	/**
	 * 查看图片
	 * @param request
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/viewImageBinarry.do")
	public void  viewImageBinarry(HttpServletRequest request,ModelMap model,HttpServletResponse response) throws IOException{
		String id = request.getParameter("id"); 
		HsdImages imagesInfo = (HsdImages)hpdataService.findByID(HsdImages.class, id);
 		byte[] img =  imagesInfo.getContent() ;        //将查询到的blob转化成byte[]
	    
	    response.setContentType( "image/jpeg ");                                     
	    response.setContentLength(img.length);        

//	    InputStream inputStream =imagesInfo.getContent() .ge// IO流
//	    int length = (int) blob.length();
//	    byte[] b = new byte[length];
//	    inputStream.read(b, 0, length);
//	    PrintWriter out = resp.getWriter();
//	    InputStream is = new ByteArrayInputStream(b);
//	    int a = is.read();
//	    while (a != -1) {
//	         out.print((char) a);
//	         a = is.read();
//	     }
//	    out.flush();
//	    out.close();
	    try { 
		    ServletOutputStream   ss   =   response.getOutputStream();   
		    ss.write(img);               
		    ss.flush(); 
	    } catch (IOException e) { 
	        e.printStackTrace(); 
	    } 
	}
	
	/**
	 * 从图片库中查询符合条件的图片
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/searchImages.do",produces = {"application/json;charset=UTF-8"})
	public @ResponseBody String searchImages(HttpServletRequest request,ModelMap model,HttpServletResponse response) throws IOException{
		String searchTxt = request.getParameter("searchTxt");  
		PageParams pageParams = new PageParams();
		pageParams.setPageSize(20);
		pageParams.setPageNo(1);
		Pagination page = this.hpdataService.searchImagesList(pageParams,searchTxt);
		
		List list = page.getList();
		JSONArray array = new JSONArray();
		if(null != list){
			for(Object obj : list){
				JSONObject json = new JSONObject();
				HsdImages image = (HsdImages)obj;
				json.put("imageUrl", image.getId());
				json.put("title", image.getNamestr());
				array.add(json);
			}
		}
		return array.toString();
	}
	
	@RequestMapping(value="/swfUploadFile.do")
	public void swrUploadFile(HttpServletRequest request,ModelMap model,HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		UeditorUploader up = new UeditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(50000); //单位KB
        up.upload();
        
        HsdImages imagesInfo = up.getHsdImage();
        imagesInfo.setId(UUIDGenerator.getUUID());
        imagesInfo.setOpertime(TimeUtil.getCurrentDate());
        HsdAccount accInfo = this.getCurrentuser(request);
        if(null != accInfo){
			imagesInfo.setUserid(accInfo.getId());
			imagesInfo.setUsername(accInfo.getUsername());
		}
        hpdataService.save(imagesInfo);
		response.getWriter().print("{'original':'"+up.getOriginalName()+"','url':'"+imagesInfo.getId()+"','title':'"+imagesInfo.getNamestr()+"','state':'"+up.getState()+"'}");
	}
}
